<?php
/**
 * @author Victor Cardenas
 * Clase para elementos de formulario con autocompletado
 * para ubicacion de ciudad
 *
 */
class App_Form_Element_Autocompletar extends Zend_Form_Element_Text {
    
    protected $_value_field_name;
    protected $_url_json;
    protected $_extraParams;
    
    /**
     * Elemento de textfield con autocompletado
     * @param string $spec
     * @param string $value_field_name
     * @param string $url_json
     * @param mixed string|array optional $extraParams
     * @param array optional $options
     */
    public function __construct($spec, $value_field_name, $url_json, $extraParams=null, $options = null) {
        $this->_type = "Zend_Form_Element_Text";
        parent::__construct($spec, $options);
        $this->_value_field_name = $value_field_name;
        $this->_url_json = $url_json;
        $this->_extraParams = $extraParams;
    }

    public function render(Zend_View_Interface $view = null) {
        $content = parent::render($view);
        if(empty($content)) {
            return $content;
        }
        $baseUrl = Zend_Controller_Front::getInstance ()->getBaseUrl();
        $content .= "<script type=\"text/javascript\">";
        $content .= "$(function() {";
        $content .=   "$(\"#{$this->getId()}\").autocomplete({";
        $content .=     "delay: 400,";
        $content .=     "minLength: 3,";
        if(empty($this->_extraParams)) {
            $content .=     "source: \"{$baseUrl}{$this->_url_json}\",";
            
        } else {
            $params = (array)$this->_extraParams;
            $data = array();
            $data[] = "term : request.term";
            foreach($params as $value) {
                $data[] = "{$value}:$(\"#{$value}\").val()";
            }
            $content .=     "source: function( request, response ) {";
            $content .=     	"$.ajax({url: \"{$baseUrl}{$this->_url_json}\",";
            $content .=     		"data: { ".join(",", $data)." },";
            $content .=     		"dataType: \"json\",";
            $content .=     		"success: function(data) {response(data);},";
            $content .=     		"error: function() {response([]);}";
            $content .=     	"});";
            $content .=     "},";
        }
        $content .=     "focus: function(event, ui) {";
        $content .=       "event.preventDefault();";
        $content .=       "(this).val(ui.item.label);";
        $content .=     "},";
        $content .=     "select: function(event, ui) {";
        $content .=       "event.preventDefault();";
        $content .=       "$(this).val(ui.item.label);";
        $content .=       "$(\"#{$this->_value_field_name}\").val(ui.item.value);";
        $content .=     "},";
        $content .=   "});";
        $content .= "});";
        $content .= "</script>";
        return $content;
    }
    
    
}
